package particles;

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Stage;
import flash.display.StageScaleMode;

import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldAutoSize;

import flash.events.MouseEvent;
import flash.events.Event;

class FlashRenderer
{
	var stage : Stage;
	var bitmapData : BitmapData;
	var bitmap : Bitmap;
	
	var text : TextField;
	var model : EngineModel;
	var lastFrameTime : Float;
	
	public function new(model : EngineModel)
	{
		this.model = model;
		stage = flash.Lib.current.stage;
		stage.frameRate = 30;
		stage.scaleMode = StageScaleMode.NO_SCALE;
		
		stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);
		stage.addEventListener(Event.RESIZE, handleStageResize);
		
		bitmap = new Bitmap();
		flash.Lib.current.addChild(bitmap);
		
		text = new TextField();
		text.defaultTextFormat = new TextFormat("Arial", 10, 0x00ff00);
		text.selectable = false;
		text.autoSize = TextFieldAutoSize.LEFT;
		text.text = "Hallo";
		
		flash.Lib.current.addChild(text);
		
		updateSize();
	}
	
	public function render()
	{
		model.time = Date.now().getTime();
		text.text = "FPS: " + Std.int(1000 / (model.time - lastFrameTime));
		lastFrameTime = model.time;
		
		var mc = flash.Lib.current;
		
		bitmapData.fillRect(bitmapData.rect, 0x000000);
		
		for (particle in model.particles)
		{
			bitmapData.setPixel(Std.int(particle.x / 2), Std.int(particle.y / 2), 0xffffff);
		}
	}
	
	function handleMouseMove(event : MouseEvent)
	{
		model.mouseX = Std.int(stage.mouseX);
		model.mouseY = Std.int(stage.mouseY);
	}
	
	function handleStageResize(event : Event)
	{
		updateSize();
	}
	
	function updateSize()
	{
		model.width = Std.int(stage.stageWidth);
		model.height = Std.int(stage.stageHeight);
		
		bitmapData = new BitmapData(model.width, model.height, false, 0x0);
		bitmap.bitmapData = bitmapData; 
	}
}
